﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using CAUNetLogin.NetUtil.ReturnMessage;
using CAUNetLogin.Entity;

namespace CAUNetLogin.Util.Entity
{
    /// <summary>
    /// 网络连接断开
    /// </summary>
    public class NetConnect
    {
        public string lastErrorMesage = "";
        public bool isError = false;

        /// <summary>
        /// 连接网关
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <param name="result">返回详细结果，需要进行解析才知道参数信息</param>
        /// <returns>连接网络成功与否</returns>
        public bool ConnectSucceed(Account user, ref string result)
        {
            try
            {
                string postData = "0MKKey=login&DDDDD=" + user.User + "&upass=" + user.Password;
                string url = "http://202.205.80.10/";
                string info = "";
                if (GetHtmlByPostMethod(url, postData, ref info))
                {
                    if (info.Contains("logged successfully"))//登录成功
                    {
                        isError = !GetHtmlByGetMethod(@"http://202.205.80.10/1.htm", ref result);
                        return !isError;
                    }
                    else if (info.Contains("Msg=02")) //该账号在其他机子使用
                    {
                        postData = "DDDDD=" + user.User + "&upass=" + user.Password + "&AMKKey=&v6ip=";//也可直接使用此办法
                        if (GetHtmlByPostMethod(url, postData, ref info))
                        {
                            if (info.Contains("logged successfully"))
                            {
                                isError = !GetHtmlByGetMethod(@"http://202.205.80.10/1.htm", ref result);
                                return !isError;
                            }
                        }
                        result = info;
                        return false;
                    }
                    else//其他错误
                    {
                        result = info;
                        return false;
                    }
                }
                else
                {
                    isError = true;
                    return false;
                }
            }
            catch (Exception ex)
            {
                isError = true;
                lastErrorMesage = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 获取流量信息
        /// </summary>
        /// <param name="result">返回的结果</param>
        /// <returns>是否获取成功</returns>
        public bool GetFlowInfo(ref string result)
        {
            if (GetHtmlByGetMethod("http://202.205.80.10", ref result))
            {
                if (result.Contains("您已经登录成功"))
                    return true;
            }
            return false;
        }
        /// <summary>
        /// 断开网络
        /// </summary>
        /// <returns>断开成功与否</returns>
        public bool DisConnect()
        {
            try
            {
                string url = "http://auth.cau.edu.cn/F.htm";
                WebClient webClient = new WebClient();
                webClient.Proxy = null;
                Stream stream = webClient.OpenRead(url);
                StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("gb2312"));
                string info = sr.ReadToEnd();
                sr.Close();
                if (info.Contains("Msg=14;time"))
                {
                    isError = false;
                    return true;
                }
                else
                {
                    isError = true;
                    lastErrorMesage = "断开连接失败";
                    return false;
                }
            }
            catch (Exception ex)
            {
                isError = true;
                lastErrorMesage = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 通过GET方式获取某一个网页的内容（GB2312编码）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public bool GetHtmlByGetMethod(string url, ref string result)
        {
            try
            {
                WebClient webClient = new WebClient();
                webClient.Proxy = null;
                Stream stream = webClient.OpenRead(url);
                StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("gb2312"));
                result = sr.ReadToEnd();
                sr.Close();
            }
            catch (Exception ex)
            {
                lastErrorMesage = ex.Message;
                return false;
            }
            return true;
        }

        /// <summary>
        /// 通过POST方式获取某一个网页的内容（GB2312编码）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public bool GetHtmlByPostMethod(string url, string postData, ref string result)
        {
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;
                request.Proxy = null;
                Stream stream = request.GetRequestStream();
                stream.Write(byteArray, 0, byteArray.Length);
                stream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gb2312"));
                result = reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                lastErrorMesage = ex.Message;
                return false;
            }
            return true;
        }
    }
}
